<template>
  <div>
    <el-row>
      <el-button type="primary" @click="openDialog('add')" label-position="left">新增热门专题</el-button>
      <el-dialog
        :title="dialogType==='add'?'新增热门专题':'编辑专题'"
        :visible.sync="dialogFormVisible"
        :append-to-body="true"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :before-close="closeDialog"
      >
        <el-form :model="form" :rules="rules" ref="form">
          <el-form-item label="专题名称" :label-width="formLabelWidth" prop="name">
            <el-input v-model="form.name" autocomplete="off" placeholder="请输入专题名称"></el-input>
          </el-form-item>
          <el-form-item
            label="图片地址"
            :label-width="formLabelWidth"
            style="width:80%;"
            prop="thumbnail"
          >
            <el-upload
              class="avatar-uploader"
              :action="uploadImageUrl"
              accept="image/jpeg, image/png, image/jpg"
              :show-file-list="false"
              :on-success="handleUploadSuccess"
              :data="{'dir':'special_topic'}"
              :before-upload="beforeUpload"
              :with-credentials="true"
            >
              <img
                v-if="form.thumbnail"
                style="width:150px;border:none;"
                :src="form.thumbnail|getStaticImg"
                class="avatar"
              />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="排序" :label-width="formLabelWidth" prop="sort">
            <el-input v-model="form.sort" autocomplete="off" disabled></el-input>
          </el-form-item>
          <el-form-item label="是否开启" :label-width="formLabelWidth" prop="status">
            <el-select v-model="form.status" placeholder="请选择状态" style="width:100%">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="跳转类型" :label-width="formLabelWidth" prop="link_type">
            <el-select
              v-model="form.link_type"
              placeholder="请选择跳转类型"
              style="width:100%"
              @change="changeTypes"
            >
              <el-option
                v-for="item in changeOptions"
                :key="item.link_type"
                :label="item.label"
                :value="item.link_type"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            v-if="form.link_type==4"
            label="跳转链接"
            :label-width="formLabelWidth"
            prop="link"
          >
            <el-input v-model="form.link" autocomplete="off" placeholder="请输入跳转链接"></el-input>
          </el-form-item>
          <el-form-item
            v-if="form.link_type&&form.link_type!=4"
            :label="form.link_type==1?'跳转分类':form.link_type==2?'跳转标签':form.link_type==3?'跳转专题':''"
            :label-width="formLabelWidth"
            prop="link_name"
          >
            <el-autocomplete
              v-model="form.link_name"
              v-if="form.link_type==1"
              style="width:100%;"
              :fetch-suggestions="queryCategory"
              placeholder="请输入分类id或名称"
              @select="handleSelectLink"
            ></el-autocomplete>
            <el-autocomplete
              v-model="form.link_name"
              v-if="form.link_type==2"
              style="width:100%;"
              :fetch-suggestions="queryTags"
              placeholder="请输入标签id或名称"
              @select="handleSelectLink"
            ></el-autocomplete>
            <el-autocomplete
              v-model="form.link_name"
              v-if="form.link_type==3"
              style="width:100%;"
              :fetch-suggestions="queryTopic"
              placeholder="请输入专题id或名称"
              @select="handleSelectLink"
            ></el-autocomplete>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="closeDialog()">取 消</el-button>
          <el-button
            type="primary"
            :loading="button_loading"
            @click="dialogType=='add'?addHot('form'):submitEdit('form')"
          >确 定</el-button>
        </span>
      </el-dialog>
    </el-row>

    <el-table
      align="center"
      ref="multipleTable"
      :data="hotTopicList"
      tooltip-effect="dark"
      row-key="id"
      style="width: 100%;margin-top:15px"
      :default-sort="{prop: 'sort', order: 'ascending'}"
      @selection-change="handleSelectionChange"
    >
      <el-table-column prop="id" label="ID" width="50"></el-table-column>
      <el-table-column prop="name" label="文案名称"></el-table-column>
      <el-table-column min-width="120" prop="thumbnail" label="图片展示" align="center">
        <template slot-scope="scope">
          <a :href="scope.row.thumbnail|getStaticImg" target="_blank">
            <img style="width:150px;border:none;" :src="scope.row.thumbnail|getStaticImg" />
          </a>
        </template>
      </el-table-column>
      <!-- <el-table-column min-width="120" prop="thumbnail" label="图片展示" align="center">
        <template slot-scope="scope">
          <el-popover placement="right" trigger="click">
            <el-image :src="scope.row.thumbnail|getStaticImg" fit="contain"></el-image>
            <el-button slot="reference" style="padding:0;margin:0;border-radio:0;border:none;">
              <img style="width:150px;border:none;" :src="scope.row.thumbnail|getStaticImg" />
            </el-button>
          </el-popover>
      </template>-->
      <!-- <template slot-scope="scope">
          <el-image :src="scope.row.thumbnail" fit="contain" style="width:150px;height:150px;"></el-image>
      </template>-->
      <!-- </el-table-column> -->
      <el-table-column prop="status" label="显示状态">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.statusBool"
            active-text="开启"
            inactive-text="关闭"
            @change="modifyStatus($event, scope.row.id)"
            active-color="#13ce66"
            inactive-color="#ff4949"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="link_type" label="跳转类型">
        <template slot-scope="scope">
          <p>{{parseInt(scope.row.link_type)|linkTypeFilter}}</p>
        </template>
      </el-table-column>
      <el-table-column prop="link_id" label="跳转id/链接">
        <template slot-scope="scope">
          <div v-if="scope.row.link_type!=4">
            {{scope.row.link_type==1?'分类':scope.row.link_type==2?'标签':'专题'}}
            <span>-{{scope.row.link_name}} id：{{scope.row.link_id}}</span>
          </div>
          <div v-if="scope.row.link_type==4">
            链接：
            <a :href="scope.row.link" target="_blank">{{scope.row.link}}</a>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="sort" label="排序" width="50"></el-table-column>
      <el-table-column label="编辑修改" align="center">
        <template slot-scope="scope">
          <el-button type="text" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="text" @click="deleteTopic(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>
<script>
import Cookies from 'js-cookie'
import Sortable from "sortablejs";
import { typeSelects } from "@/utils/sel_dict";
import { queryCategory, queryTags, queryTopic } from "@/utils/query";

export default {
  data() {
    return {
      uploadImageUrl: `${process.env.VUE_APP_BASE_API}/up/uploadlink?_csrf=${Cookies.get('X-CSRF-TOKEN')}`,
      rules: {
        name: [{ required: true, message: "请输入专题名称", trigger: "blur" }],
        thumbnail: [
          { required: true, message: "请输入图片地址", trigger: "blur" }
        ],
        status: [{ required: true, message: "请选择状态", trigger: "blur" }],
        sort: [{ required: true, message: "请输入排序号", trigger: "change" }],
        link: [{ required: true, message: "请输入链接", trigger: "change" }],
        link_id: [{ required: true, message: "请输入链接id", trigger: "blur" }],
        link_type: [
          { required: true, message: "请输入连接类型", trigger: "change" }
        ],
        link_name: [
          {
            required: true,
            message: "请输入跳转类型ID/链接",
            trigger: "change"
          }
        ]
      },
      hotTopicList: [],
      multipleSelection: [],
      changeOptions: typeSelects,
      dialogFormVisible: false,
      button_loading: false,
      dialogType: "add",
      formLabelWidth: "120px",
      form: {
        name: "", //专题名称
        thumbnail: "", //图片展示地址
        status: 0, //状态0开启，1关闭
        sort: "", //排序
        link: "", //跳转链接
        link_id: "", //对应跳转类型的id
        link_name: "",
        link_type: "" //链接类型
      },
      options: [
        { value: 0, label: "开启" },
        { value: 1, label: "关闭" }
      ]
    };
  },

  mounted() {
    this.rowDrop();
    this.getHotTopics();
  },
  methods: {
    queryCategory(...args) {
      return queryCategory.call(this, ...args);
    },
    queryTags(...args) {
      return queryTags.call(this, ...args);
    },
    queryTopic(...args) {
      return queryTopic.call(this, ...args);
    },

    beforeUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB!");
      }
      return isLt2M;
    },
    handleUploadSuccess(res) {
      this.form.thumbnail = res.title;
    },

    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    initForm() {
      return (this.form = {
        name: "", //专题名称
        thumbnail: "", //图片展示地址
        status: 0, //状态0开启，1关闭
        sort: "", //排序
        link: "", //跳转链接
        link_id: "", //对应跳转类型的id
        link_name: "",
        link_type: "" //链接类型
      });
    },

    closeDialog() {
      this.dialogFormVisible = false;
      this.$refs.form.resetFields();
      this.initForm();
    },

    //选中某个ID跳转
    handleSelectLink(item) {
      if (item.id == -1) {
        this.form.link_id = "";
        this.form.link_name = "";
        return;
      }
      this.form.link_id = item.id;
      this.form.link = "";
    },

    //更改跳转分类类型,每次选择清空上次选择
    changeTypes() {
      this.form.link = "";
      this.form.link_id = "";
      this.form.link_name = "";
    },

    // 打开编辑专题
    handleEdit(item) {
      this.dialogFormVisible = true;
      this.dialogType = "edit";
      Object.assign(this.form, item);
      // if( item.link_id !== null ){
      //   this.form.link_id = item.link_id.toString();
      // }
    },

    openDialog() {
      this.axios.get("/specialTopic/getHotCount").then(res => {
        this.form.sort = res + 1;
        this.dialogType = "add";
        this.dialogFormVisible = true;
      });
    },

    //行拖拽排序
    rowDrop() {
      const tbody = document.querySelector(".el-table__body-wrapper tbody");
      const _this = this;
      Sortable.create(tbody, {
        onEnd({ newIndex, oldIndex }) {
          const currRow = _this.hotTopicList.splice(oldIndex, 1)[0];
          _this.hotTopicList.splice(newIndex, 0, currRow);
          if (newIndex === oldIndex) {
            return;
          }
          _this.axios
            .post("/specialTopic/hotSort", {
              params: {
                start: newIndex,
                end: oldIndex
              }
            })
            .then(res => {
              if (res != undefined) {
                _this.$message.success("已经更新顺序");
                _this.getHotTopics();
              } else {
                _this.$message.error("排序失败");
              }
            });
        }
      });
    },

    // 提交编辑
    submitEdit(formName) {
      this.button_loading = true;
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (this.form.link_type !== 4 && this.form.link_id == "") {
            this.$message.info(
              "跳转内容有误，请在输入后点击输入框提示的内容！"
            );
            return false;
          }
          this.axios({
            method: "post",
            url: "/specialTopic/editHotTopics",
            data: this.form
          })
            .then(res => {
              if (res) {
                this.dialogFormVisible = false;
                this.$message.success("更新成功");
                this.closeDialog();
                this.getHotTopics();
                this.button_loading = false;
              } else {
                this.$message.info("更新失败");
                this.button_loading = false;
              }
            })
            .catch(err => {
              console.log(err);
            });
        }
      });
    },

    //添加热门专题
    addHot(formName) {
      this.button_loading = true;
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (this.form.link_type !== 4 && this.form.link_id == "") {
            this.$message.info(
              "跳转内容有误，请在输入后点击输入框提示的内容！"
            );
            this.button_loading = false;
            return false;
          }
          this.axios({
            method: "post",
            url: "/specialTopic/addHotTopics",
            data: this.form
          })
            .then(res => {
              if (res) {
                this.dialogFormVisible = false;
                this.closeDialog();
                this.getHotTopics();
                this.$message.success("添加成功");
                this.button_loading = false;
              } else {
                this.$message.error("添加失败");
                this.button_loading = false;
              }
            })
            .catch(err => {
              console.log(err);
              this.button_loading = false;
            });
        } else {
          this.button_loading = false;
          return false;
        }
      });
    },

    // 删除专题
    deleteTopic(item) {
      this.$confirm(`是否删除 "${item.name}" 专题?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.axios({
          url: "/specialTopic/deleteHotTopic",
          method: "post",
          data: item
        }).then(res => {
          if (res) {
            this.$message({
              type: "success",
              message: "删除成功"
            });
            this.getHotTopics();
          } else {
            this.$message.error("删除失败");
          }
        });
      });
    },

    // 获取热门专题列表
    getHotTopics() {
      this.axios({
        method: "get",
        url: "/specialTopic/getHotTopics"
      })
        .then(res => {
          for (let row of res.rows) {
            row.statusBool = row.status == 0;
          }
          this.hotTopicList = res.rows;
        })
        .catch(err => {
          console.log(err);
        });
    },

    //修改状态
    modifyStatus(status, id) {
      var params = { id };
      if (status) {
        params.status = 0;
      } else {
        params.status = 1;
      }

      this.axios
        .post("/specialTopic/modifyStatus", params)
        .then(res => {
          if (res[0] > 0) {
            this.getHotTopics();
          }
        })
        .catch(err => {
          console.log(err);
        });
    }
  }
};
</script>
<style lang="scss" scoped>
.move {
  border: 1px solid #ddd;
  border-radius: 3px;
  width: 100%;
  height: 100%;
}
</style>